<template>
    <div class="add_account">
        <div class="c-flex c-a-c top">
            <h2 class="title">添加商品（游戏加速器）</h2>
            <div class="upload" v-if="menuShow">
                <el-button type="primary" @click="goUpload">导入商品</el-button>
                <el-button type="primary" @click="openSupplier">库存供货设置</el-button>
                <el-button type="primary" @click="openMode">供货模式设置</el-button>
            </div>
        </div>
        <el-form :model="addForm" :rules="addrules" ref="addForm" label-width="100px" class="demo-ruleForm">
            <el-form-item label="商品名称" prop="goodsName">
                <el-input v-model="addForm.goodsName" placeholder="请输入游戏名称，最多15个字"></el-input>
            </el-form-item>
            <el-form-item label="商品副标题" prop="goodsDescribe">
                <el-input v-model="addForm.goodsDescribe" placeholder="请输入商品副标题，最多30个字"></el-input>
            </el-form-item>
            <el-form-item label="上架内容">
                <el-button :class="{ active: isActive==1 }" @click="iscarousel = true;isActive=1;">轮播图</el-button>
                <el-button :class="{ active: isActive==2 }" @click="iscarousel = false;isActive=2;">详情图</el-button>
            </el-form-item>
            <el-form-item label="图片上传">
                <div v-if="iscarousel" class="c-flex">
                    <div class="upload_pic">
                        <el-upload class="avatar-uploader" action="http://wyds.new.91wangjing.com/common/fileUpload"
                            :show-file-list="false" :on-success="handleAvatarSuccessZ" :before-upload="beforeAvatarUpload">
                            <img v-if="imgZ" :src="imgZ" class="avatar">
                            <i v-else class="el-icon-plus avatar-uploader-icon">添加主图</i>
                        </el-upload>
                    </div>
                    <div class="upload_pic">
                        <el-upload class="avatar-uploader" action="http://wyds.new.91wangjing.com/common/fileUpload"
                            :show-file-list="false" :on-success="handleAvatarSuccessL1" :before-upload="beforeAvatarUpload">
                            <img v-if="imgL1" :src="imgL1" class="avatar">
                            <i v-else class="el-icon-plus avatar-uploader-icon">添加轮播图</i>
                        </el-upload>
                    </div>
                    <div class="upload_pic">
                        <el-upload class="avatar-uploader" action="http://wyds.new.91wangjing.com/common/fileUpload"
                            :show-file-list="false" :on-success="handleAvatarSuccessL2" :before-upload="beforeAvatarUpload">
                            <img v-if="imgL2" :src="imgL2" class="avatar">
                            <i v-else class="el-icon-plus avatar-uploader-icon">添加轮播图</i>
                        </el-upload>
                    </div>
                </div>
                <div v-else>
                    <div class="upload_pic">
                        <el-upload class="avatar-uploader" action="http://wyds.new.91wangjing.com/common/fileUpload"
                            :show-file-list="false" :on-success="handleAvatarSuccessX" :before-upload="beforeAvatarUpload">
                            <img v-if="addForm.goodsUrl" :src="addForm.goodsUrl" class="avatar">
                            <i v-else class="el-icon-plus avatar-uploader-icon">添加详情图</i>
                        </el-upload>
                    </div>
                </div>
            </el-form-item>
            <el-form-item label="商品标价" prop="price">
                    <el-input v-model="addForm.price" placeholder="请输入商品标价（仅展示用）"></el-input>
                </el-form-item>
            <el-form-item label="售价" prop="truthAmount">
                <el-input v-model="addForm.truthAmount" placeholder="请输入正常售价"></el-input>
            </el-form-item>
            <el-form-item label="会员价" prop="vipAmount">
                <el-input v-model="addForm.vipAmount" placeholder="请输入会员价（仅展示用）"></el-input>
            </el-form-item>
            <el-form-item label="规格" prop="explains">
                    <div id="editorElem"></div>
                </el-form-item>
            <el-form-item label="供应商" prop="menuThree">
                <el-select v-model="addForm.menuThree" placeholder="请选择供应商">
                    <el-option v-for="item in optionsSupplier" :key="item.id" :label="item.name" :value="item.id">
                    </el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="商品基础销量" prop="baseSales">
                <el-input v-model="addForm.baseSales" placeholder="请输入商品基础销量（仅展示用）"></el-input>
            </el-form-item>
            <el-form-item label="API接口编号" prop="apiId">
                <el-input v-model="addForm.apiId"></el-input>
            </el-form-item>
            <el-form-item label="是否支持退款" prop="refund">
                <el-switch v-model="addForm.refund"></el-switch>
            </el-form-item>
            <el-form-item label="是否立即上架" prop="goodsState">
                <el-switch v-model="addForm.goodsState"></el-switch>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="submitForm('addForm')" v-if="isAdd">立即添加</el-button>
                <el-button type="primary" @click="changeForm('addForm')" v-else>修改</el-button>
                <el-button @click="quitForm()">取消</el-button>
            </el-form-item>
        </el-form>
        <el-dialog title="游戏账号导入" :visible.sync="importVisible" width="60%">
            <el-form :model="importForm" :rules="importrules" ref="importForm" label-width="100px" class="demo-ruleForm">
                <el-form-item label="游戏名称" prop="gameNameId">
                    <el-select v-model="importForm.gameNameId" placeholder="请选择游戏名称">
                        <el-option v-for="item in optionsPlat" :key="item.id" :label="item.name" :value="item.id">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="供应商" prop="supplierId">
                    <el-select v-model="importForm.supplierId" placeholder="请选择供应商">
                        <el-option v-for="item in optionsSupplier" :key="item.id" :label="item.name" :value="item.id">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="上传附件">
                    <el-upload class="upload-demo" action="123" :on-change="handleChange" :file-list="importForm.file"
                        :before-upload="beforeFileUpload">
                        <el-button size="small" type="primary">点击上传</el-button>
                        <div slot="tip" class="el-upload__tip">支持扩展名：.xlsx</div>
                    </el-upload>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="importVisible = false">取 消</el-button>
                <el-button type="primary" @click="submitImport()">提交</el-button>
            </span>
        </el-dialog>

        <el-dialog title="库存供货设置" :visible.sync="supplierVisible" width="60%">
            <div class="account_lists">
                <template>
                    <el-table :data="supplierData" border style="width: 100%">
                        <el-table-column prop="name" label="供应商">
                        </el-table-column>
                        <el-table-column prop="stock" label="库存(件)">
                        </el-table-column>
                        <el-table-column fixed="right" label="操作">
                            <template slot-scope="scope">
                                <el-button type="text" size="small" v-if="scope.row.enabled" @click="goForbidden(scope.row.id)">启用</el-button>
                                <el-button type="text" size="small" @click="goStart(scope.row.id)" v-else>禁用</el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                </template>
            </div>
            <span slot="footer" class="dialog-footer">
                <el-button @click="supplierVisible = false">取 消</el-button>
                <el-button type="primary" @click="centerDialogVisible = false">确 定</el-button>
            </span>
        </el-dialog>
        <el-dialog title="供货模式设置" :visible.sync="modeVisible" width="60%">
            <div>
                <template>
                    <el-radio v-model="modeRadio" label="1">AIP供货模式</el-radio>
                    <el-radio v-model="modeRadio" label="2">库存供货模式</el-radio>
                </template>
            </div>
            <span slot="footer" class="dialog-footer">
                <el-button @click="supplierVisible = false">取 消</el-button>
                <el-button type="primary" @click="goModecheck">确 定</el-button>
            </span>
        </el-dialog>
    </div>
</template>
<script>
    import E from 'wangeditor'
    export default {
        data() {
            return {
                menuShow: false,
                isAdd: true,
                isActive: 1,
                imgZ: '',
                imgL1: '',
                imgL2: '',
                imgX: '',
                optionsPlat: [],
                optionsName: [],
                optionsSupplier: [],
                dialogVisible: false,
                dialogImageUrl: '',
                iscarousel: true,
                supplierVisible: false,      //库存供货设置
                supplierData: [],           //库存供货data
                modeVisible: false,            //供货模式设置
                modeRadio: '1',
                addForm: {
                    goodsUrl: '',
                    goodsState: true,
                },
                addrules: {
                    goodsName: [
                        { required: true, message: '请输入商品名称', trigger: 'blur' },
                        { max: 15, message: '请输入游戏名称，最多15个字', trigger: 'blur' }
                    ],
                    goodsDescribe: [
                        { required: true, message: '请输入商品副标题', trigger: 'blur' },
                        { max: 15, message: '请输入商品副标题，最多30个字', trigger: 'blur' }
                    ],
                    price: [
                        { required: true, message: '请输入商品标价', trigger: 'blur' }
                    ],
                    truthAmount: [
                        { required: true, message: '请输入售价', trigger: 'blur' }
                    ],
                    vipAmount: [
                        { required: true, message: '请输入会员价', trigger: 'blur' }
                    ],
                    menuThree: [
                        { required: true, message: '请选择供应商', trigger: 'change' }
                    ],
                    baseSales: [
                        { required: true, message: '请输入商品基础销量', trigger: 'blur' }
                    ],
                },
                importForm: {
                },
                importrules: {
                    plat: [
                        { required: true, message: '请选择游戏平台', trigger: 'change' }
                    ],
                    name: [
                        { required: true, message: '请选择游戏名称', trigger: 'change' }
                    ],
                    supplier: [
                        { required: true, message: '请选择供应商', trigger: 'change' }
                    ],
                    stockPrice: [
                        { required: true, message: '请输入进货价格', trigger: 'blur' }
                    ],
                },
                importVisible: false,
                dataRm: '',
            };
        },
        mounted() {
            var editor = new E('#editorElem')
            editor.customConfig.onchange = (html) => {
                this.addForm.explains = html
            }
            editor.create();
            //1 游戏平台  2 游戏名称   3 供应商
            var _this = this;
            var options_a = {}, options_b = {}, options_c = {};
            options_a.id = 1;
            options_b.id = 2;
            options_c.id = 3;

            function getOptionsA() {
                return _this.axios.get('shop/classify/classifyMenuList', { params: options_a });
            }

            function getOptionsB() {
                return _this.axios.get('shop/classify/classifyMenuList', { params: options_b });
            }

            function getOptionsC() {
                return _this.axios.get('shop/classify/classifyMenuList', { params: options_c });
            }

            _this.axios.all([getOptionsA(), getOptionsB(), getOptionsC()])
                .then(_this.axios.spread(function (optionsa, optionsb, optionsc) {
                    _this.optionsPlat = optionsa.data.data;
                    _this.optionsName = optionsb.data.data;
                    _this.optionsSupplier = optionsc.data.data;
                    var _id = _this.$route.query.id;
                    if (_id) {
                        _this.menuShow = true;
                        _this.isAdd = false;
                        var params = {};
                        params.id = _id;
                        _this.axios
                            .get("spGoods/gameBoosterDetail", { params: params })
                            .then(res => {
                                var _data = res.data;
                                if (_data.code == 200) {
                                    _this.addForm = _data.data;
                                    editor.txt.html( _this.addForm.explains);
                                    
                                    var _imgarry = _this.addForm.goodsImg.split(',');
                                    _this.imgZ = _imgarry[0];
                                    _this.imgL1 = _imgarry[1];
                                    _this.imgL2 = _imgarry[2];

                                    //sb传字符串
                                    if (_this.addForm.refund == 'YES') {
                                        _this.addForm.refund = true;
                                    } else {
                                        _this.addForm.refund = false;
                                    }
                                    if (_this.addForm.goodsState == 'ONLINE') {
                                        _this.addForm.goodsState = true
                                    } else {
                                        _this.addForm.goodsState = false
                                    }
                                    if (_this.addForm.getType == 'YES') {
                                        _this.modeRadio = '1';
                                    } else {
                                        _this.modeRadio = '2';
                                    }
                                }
                            })
                            .catch(error => console.log(error));
                    }
                }));
        },

        methods: {
            goUpload() {
                this.importVisible = true;
            },
            //上传主图
            handleAvatarSuccessZ(res, file) {
                // this.imgZ = URL.createObjectURL(file.raw);
                this.imgZ = res.data;
            },
            //上传轮播图1
            handleAvatarSuccessL1(res, file) {
                this.imgL1 = res.data;;
            },
            //上传轮播图2
            handleAvatarSuccessL2(res, file) {
                this.imgL2 = res.data;
            },
            //上传详情图
            handleAvatarSuccessX(res, file) {
                this.addForm.goodsUrl = res.data;
                console.log(this.addForm.goodsUrl)
            },
            //上传图片
            beforeAvatarUpload(file) {
                const isJPG = file.type === 'image/jpeg';
                const isLt2M = file.size / 1024 / 1024 < 2;

                if (!isJPG) {
                    this.$message.error('上传头像图片只能是 JPG 格式!');
                }
                if (!isLt2M) {
                    this.$message.error('上传头像图片大小不能超过 2MB!');
                }
                return isJPG && isLt2M;
            },
            //上传文件
            handleChange(file, fileList) {
                if (file.response) {
                    console.log(file.response)
                    this.importForm.file = file.response.data;
                }
            },
            beforeFileUpload(file) {
                var fileName = new Array()
                fileName = file.name.split('.');
                const extension = fileName[fileName.length - 1] === 'xls'
                const extension2 = fileName[fileName.length - 1] === 'xlsx'
                const isLt2M = file.size / 1024 / 1024 < 10
                if (!extension && !extension2) {
                    this.$message({
                        message: '上传模板只能是xls、xlsx格式!',
                        type: 'warning'
                    });
                }
                if (!isLt2M) {
                    this.$message({
                        message: '上传模板大小不能超过 10MB!',
                        type: 'warning'
                    });
                    //                    console.log('上传模板大小不能超过 10MB!')
                }
                if (extension || extension2 && isLt2M == true) {
                    console.log(file)
                    let fd = new FormData()
                    fd.append('invoiceTypeId', this.invoice_type_id)//随文件上传的其他参数
                    fd.append('epid', this.epid)
                    fd.append('file', file)
                    // console.log(fd)
                    this.newImport(fd).then(function (res) {//校验完成后提交
                        console.log(res)
                    }, function () {
                        console.log('failed');
                    });
                    return true
                }
                return extension || extension2 && isLt2M
            },
            //导入文件
            newImport(data) {
                this.axios
                    .post("http://wyds.new.91wangjing.com/shop/excel/aImportExcel", data)
                    .then(res => {
                        var _data = res.data;
                        if (_data.code == 200) {
                            this.dataRm = _data.data;
                            this.$message({
                                message: '上传成功！',
                                type: 'success'
                            });
                        } else {
                            this.$message.error(_data.message);
                        }
                    })
                    .catch(error => console.log(error));
            },
            //库存供货设置
            openSupplier() {
                this.supplierVisible = true;
                var params = {};
                params.goodsNo = this.addForm.goodsNo;
                this.axios
                    .get("shop/classify/supplierSettingsList", { params: params })
                    .then(res => {
                        var _data = res.data;
                        if (_data.code == 200) {
                            this.supplierData = _data.data;
                        }
                    })
                    .catch(error => console.log(error));
            },
            //供应商启用
            goStart(id) {
                var params = {};
                params.goodsNo = this.addForm.goodsNo;
                params.supplierId = id;
                params.type = 0;
                this.axios
                    .get("shop/classify/supplierEnable", { params: params })
                    .then(res => {
                        var _data = res.data;
                        if (_data.code == 200) {
                            this.openSupplier();
                        }
                    })
                    .catch(error => console.log(error));
            },
            //供应商禁用
            goForbidden(id) {
                var params = {};
                params.goodsNo = this.addForm.goodsNo;
                params.supplierId = id;
                params.type = 1;
                this.axios
                    .get("shop/classify/supplierEnable", { params: params })
                    .then(res => {
                        var _data = res.data;
                        if (_data.code == 200) {
                            this.openSupplier();
                        }
                    })
                    .catch(error => console.log(error));
            },
            //供货模式设置弹窗
            openMode() {
                this.modeVisible = true;
            },
            //供货模式设置
            goModecheck() {
                var params = {};
                params.goodsNo = this.addForm.goodsNo;
                params.goodsType = 'NUMBER';
                if (this.modeRadio == '1') {
                    params.getType = 'YES';
                } else {
                    params.getType = 'NO';
                }
                this.axios
                    .get("api/spGoods/isApi", { params: params })
                    .then(res => {
                        var _data = res.data;
                        if (_data.code == 200) {
                            this.$message({
                                message: '设置成功！',
                                type: 'success'
                            });
                            this.modeVisible = false;
                        }
                    })
                    .catch(error => console.log(error));
            },
            //添加商品
            submitForm(formName) {
                this.$refs[formName].validate((valid) => {
                    console.log(valid)
                    if (valid) {
                        var params = this.addForm;
                        var _imgarry = [];
                        _imgarry.splice(1, 0, this.imgZ, this.imgL1, this.imgL2);
                        params.goodsImg = _imgarry.toString();
                        params.goodsType = 'SPEED';
                        if (params.refund) {
                            params.refund = 'YES'
                        } else {
                            params.refund = 'NO'
                        }
                        if (params.goodsState) {
                            params.goodsState = 'ONLINE'
                        } else {
                            params.goodsState = 'OFFLINE'
                        }
                        this.axios
                            .post("spGoods/addGameBooster", params)
                            .then(res => {
                                var _data = res.data;
                                if (_data.code == 200) {
                                    this.$message({
                                        message: '添加成功！',
                                        type: 'success'
                                    });
                                    // this.$router.push({
                                    //     path: '/gameAccelerator'
                                    // });
                                } else {
                                    if (this.addForm.refund == 'YES') {
                                        this.addForm.refund = true;
                                    } else {
                                        this.addForm.refund = false;
                                    }
                                    if (this.addForm.goodsState == 'ONLINE') {
                                        this.addForm.goodsState = true
                                    } else {
                                        this.addForm.goodsState = false
                                    }
                                    this.$message.error(_data.message);
                                }
                            })
                            .catch(error => console.log(error));
                    } else {
                        console.log('error submit!!');
                        return false;
                    }
                });
            },
            //修改商品
            changeForm() {
                var params = this.addForm;
                var _imgarry = [];
                _imgarry.splice(1, 0, this.imgZ, this.imgL1, this.imgL2);
                params.goodsImg = _imgarry.toString();
                params.goodsType = 'SPEED';
                if (params.refund) {
                    params.refund = 'YES'
                } else {
                    params.refund = 'NO'
                }
                if (params.goodsState) {
                    params.goodsState = 'ONLINE'
                } else {
                    params.goodsState = 'OFFLINE'
                }
                this.axios
                    .post("spGoods/updateGameBooster", params)
                    .then(res => {
                        var _data = res.data;
                        if (_data.code == 200) {
                            this.$message({
                                message: '修改成功！',
                                type: 'success'
                            });
                            this.$router.push({
                                path: '/gameAccelerator'
                            });
                        } else {
                            if (params.refund) {
                                params.refund = 'YES'
                            } else {
                                params.refund = 'NO'
                            }
                            if (params.goodsState) {
                                params.goodsState = 'ONLINE'
                            } else {
                                params.goodsState = 'OFFLINE'
                            }
                            this.$message.error(_data.message);
                        }
                    })
                    .catch(error => console.log(error));
            },
            quitForm() {
                this.$router.push({
                    path: '/gameAccelerator'
                });
            },
            //导入商品
            submitImport() {
                var params = this.importForm;
                params.rm = this.dataRm;
                params.id = this.$route.query.id;
                this.axios
                    .post("shop/excel/updateImportExcelInfo", params)
                    .then(res => {
                        var _data = res.data;
                        if (_data.code == 200) {
                            this.$message({
                                message: '导入成功！',
                                type: 'success'
                            });
                            this.importVisible = false;
                        } else {
                            this.$message.error(_data.message);
                        }
                    })
                    .catch(error => console.log(error));
            }
        }
    };
</script>
<style lang="less">
    .add_account {
        .top {
            height: 60px;
            border-bottom: 1px solid #dcdcdc;
            margin: 0 0 20px 25px;
            justify-content: space-between;

            .title {
                font-size: 16px;
            }

            .upload {
                margin-right: 30px;
            }
        }

        .el-input {
            width: 300px;
        }

        .upload_pic {
            margin-right: 15px;
        }
    }
</style>